//
//  FirstCityViewController.m
//  BreadTravel
//
//  Created by 张健 on 15/12/22.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "FirstCityViewController.h"
#import "SecondCityViewController.h"
#import "CJTFirstCityTableViewCell.h"
#import "CJTFirstCityModel.h"
#import "WebViewControllerCJT.h"
#import "CJTStoryDetailHeaderView.h"
#import "CollectCityViewController.h"

@interface FirstCityViewController ()<UITableViewDataSource,UITableViewDelegate,SecondCityViewControllerDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *array;

@end

@implementation FirstCityViewController

-(void)viewWillAppear:(BOOL)animated
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
//    self.navigationItem.title = @"城市猎人带你玩";
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, WIDTH, 20)];
    titleLabel.text = @"城市猎人带你玩";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全部城市" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightAction)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全部" style:(UIBarButtonItemStylePlain) target:self action:@selector(leftAction)];
    
    self.array = [NSMutableArray array];
    
    
    
    int i = 0;
    
    [self createView];
    
}

-(void)addHeaderRefresh
{
    //当下拉时刷新该方法

    [self getData];

}

-(void)createView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:(UITableViewStyleGrouped)];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[CJTFirstCityTableViewCell class] forCellReuseIdentifier:@"cell"];

    //下拉
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
    }];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(addHeaderRefresh)];
    
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
    
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
    }];
    
    //上拉
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addHeaderRefresh)];
    
    
}

-(void)getData
{
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hub show:YES];
    hub.labelText = @"加载中";
//    [MBProgressHUD setGifWithMBProgress:@"数据加载中" toView:self.view];
//    [GiFHUD setGifWithImageName:@"pika.gif"];
//    [GiFHUD show];
    
    NSString *url1 = @"http://api.breadtrip.com/hunter/products/more/?start=0";
    
    
    [AFNetworkTool getUrl:url1 body:nil result:HXJSON headerFile:nil success:^(id result) {
        
        [self.array removeAllObjects];
        
        NSMutableDictionary *dic = result;
        NSMutableArray *array = [dic objectForKey:@"product_list"];
        for (NSMutableDictionary *dic in array) {
            
            
            CJTFirstCityModel *model = [CJTFirstCityModel modelWithDictionary:dic];
            
            
            [self.array addObject:model];
        }
        if (self.array.count != 0) {
            [self.tableView reloadData];
        }
        [hub hide:YES];
        
        /** 结束刷新状态 */
        [self.tableView.header endRefreshing];
        /** 结束刷新状态 */
        [self.tableView.footer endRefreshing];
//        [MBProgressHUD hideHUDForView:self.view];
//        [GiFHUD dismiss];
        
    } failure:^(NSError *error) {
        
        
    }];

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewControllerCJT *webVC = [[WebViewControllerCJT alloc] init];
    
    //添加push动画效果
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    transition.type = @"rippleEffect";
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    
    CJTFirstCityModel *model = self.array[indexPath.row];
    webVC.titleName = model.title;
    webVC.imageName = model.model.avatar_l;
    NSLog(@"~~ %@", model.title);
    NSLog(@"!!!!! %@", model.model.avatar_l);
    
    NSString *url = [NSString stringWithFormat:@"http://web.breadtrip.com/hunter/product/%@", model.product_id];
    webVC.webURL = url;
    [self.navigationController pushViewController:webVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CJTFirstCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    cell.model = self.array[indexPath.row];
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CJTFirstCityModel *model = self.array[indexPath.row];
    CGFloat height = [CJTFirstCityTableViewCell heightForContent:model.title];
    return height + 280;
}



-(void)leftAction
{
    SecondCityViewController *vc = [[SecondCityViewController alloc] init];
    vc.secondCityCVDelegate = self;
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:vc];
    [naVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
//    UIModalTransitionStyleCoverVertical 
//    UIModalTransitionStyleFlipHorizontal
//    UIModalTransitionStyleCrossDissolve
//    UIModalTransitionStylePartialCurl
    
    [self presentViewController:naVC animated:YES completion:^{
        
        
    }];
}


-(void)getCityDetail:(NSString *)cintName
{
    
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hub show:YES];
    hub.labelText = @"加载中";
    
    self.navigationItem.leftBarButtonItem.title = cintName;
    [self.array removeAllObjects];
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?start=0&city_name=%@&lat=38.882332558663585&lng=121.53934415009309",cintName];
    [AFNetworkTool getUrl:url body:nil result:HXJSON headerFile:nil success:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *array = [dic objectForKey:@"product_list"];
        for (NSMutableDictionary *dic in array) {
            CJTFirstCityModel *model = [CJTFirstCityModel modelWithDictionary:dic];
            
            
            [self.array addObject:model];
        }
        
        self.tableView.contentOffset = CGPointMake(0, 0);
        [self.tableView reloadData];
        
        [hub hide:YES];
    } failure:^(NSError *error) {
        
        
    }];
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    CJTStoryDetailHeaderView *view = [[CJTStoryDetailHeaderView alloc] init];
    [view.headImageView removeFromSuperview];
    [view.lineView removeFromSuperview];
    view.label.text = @"你的生活  我的旅行";
    view.label.numberOfLines = 0;
    
    
    view.label.textAlignment = NSTextAlignmentCenter;
    view.label.font = [UIFont systemFontOfSize:20];
    
    [view.label mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top).offset(30);
        make.left.mas_equalTo(@20);
        
        make.right.mas_equalTo(@(-20));
        
    }];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 80;
}


-(void)rightAction
{
    self.navigationItem.leftBarButtonItem.title = @"全部";
    self.tableView.contentOffset = CGPointMake(0, 0);
    
    [self getData];
}


////让section头 不悬停
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    //section头的高度
//    CGFloat sectionHeaderHeight = 100;
//
//    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
//    {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    }
//    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
//    {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
